# encoding=utf-8
"""
响应对象业务校验
"""
from zc_core.middlewares.proxies.proxy_facade import ProxyFacade
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request


class BizValidator(BaseValidateMiddleware):

    def __init__(self):
        super().__init__()
        self.proxy_facade = ProxyFacade()

    def validate_sku(self, request, response, spider):
        if not response.text or '提示信息-多次访问需要做题' in response.text:
            meta = request.meta
            proxy = meta.get('proxy', 'NO_PROXY')
            if proxy:
                spider.logger.info('触发反爬: proxy=%s' % proxy)
                self.proxy_facade.mark_fail(proxy)
            return retry_request(request)

        return response

    def validate_item(self, request, response, spider):
        if not response.text or '提示信息-多次访问需要做题' in response.text:
            meta = request.meta
            proxy = meta.get('proxy', 'NO_PROXY')
            if proxy:
                spider.logger.info('触发反爬: proxy=%s' % proxy)
                self.proxy_facade.mark_fail(proxy)
            return retry_request(request)

        return response
